<template>
  <div class="my-component" v-if="!showSpellingExercises">
    <div class="learning-app">
      <div v-if="words.length > 0 && !showCompletion" class="container">
        <!-- 进度指示器 -->
        <div class="progress-indicator">
          <div class="progress-bar" :style="{ width: progressPercentage + '%' }"></div>
          <span class="progress-text">{{ currentIndex + 1 }} / {{ words.length }}</span>
        </div>

        <!-- 单词展示区域 -->
        <div class="word-display">
          <h2 class="word">{{ words[currentIndex].word }}</h2>
          <div class="word-meta">
            <p class="phonetic">{{ words[currentIndex].phonetic }}</p>
            <button class="pronounce-btn" @click="pronounceWord">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path
                  d="M3 12V15C3 16.8565 3.7375 18.637 5.05025 19.9497C6.36301 21.2625 8.14348 21.9999 10 22H14C15.8565 22 17.637 21.2625 18.9497 19.9497C20.2625 18.637 21 16.8565 21 15V12"
                  stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
                <path d="M12 2V22" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round" />
                <path d="M19 5V9" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round" />
                <path d="M16 7V9" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round" />
                <path d="M5 5V9" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round" />
                <path d="M8 7V9" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                  stroke-linejoin="round" />
              </svg>
            </button>
          </div>
        </div>

        <!-- 选项区域 -->
        <ul class="options">
          <li v-for="(option, index) in shuffledOptions" :key="index" :class="{
            'option': true,
            'correct': selectedOption === option && isCorrect,
            'wrong': selectedOption === option && isWrong,
            'disabled': selectedOption !== null
          }" @click="!selectedOption && checkAnswer(option)">
            <span class="option-number">{{ index + 1 }}</span>
            <span class="option-text">{{ option.definition }}</span>
          </li>
        </ul>

        <!-- 提示按钮 -->
        <button class="hint-btn" @click="openDrawer(words[currentIndex].word)">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z"
              stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
            <path d="M12 16V12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
            <path d="M12 8H12.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"
              stroke-linejoin="round" />
          </svg>
          查看提示
        </button>
        <!-- 查看笔记 -->
        <button class="hint-btn" @click="openDrawerNote(words[currentIndex].word)" style="margin-top: 10px;">
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path
              d="M12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22Z"
              stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
            <path d="M12 16V12" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
            <path d="M12 8H12.01" stroke="currentColor" stroke-width="2" stroke-linecap="round"
              stroke-linejoin="round" />
          </svg>
          查看笔记
        </button>
      </div>

      <!-- 学习完成界面 -->
      <div v-else-if="showCompletion" class="completion-screen">
        <div class="completion-content">
          <div class="celebration-icon">🎉</div>
          <h2>学习完成！</h2>
          <p>您已经完成了本组{{ words.length }}个单词的学习</p>
          <div class="completion-actions">
            <RouterLink to="/Home" class="completion-btn home-btn">
              返回主页面
            </RouterLink>
            <!-- <button class="completion-btn restart-btn" @click="restartLearning">
              再学一组
            </button> -->
            <button class="completion-btn restart-btn" @click="showSpellingExercises = !showSpellingExercises">
              拼写练习
            </button>
          </div>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-else class="loading-state">
        <div class="spinner"></div>
        <p>正在加载单词...</p>
      </div>

      <wordDrawerTop :key="selectedWord" :word="selectedWord" :show="showDrawer" />
      <notes :key="selectedWord" :word="selectedWord" :show="showDrawerNote" :userid="userId"
        :wordData="words[currentIndex]" />
    </div>
  </div>
  <!-- <div >1111</div> -->
  <SpellingExercises v-if="showSpellingExercises" :wordData="words" />
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from "vue";
import wordDrawerTop from "../../components/wordDrawerTop.vue";
import notes from "../../components/notes.vue";
import { getUnlearnedWords, saveLearnedWords, addStudyLogDataApi } from "../../api/authService.js";
import SpellingExercises from '../../components/SpellingExercises.vue';
// 获取本地存储的用户ID
const userId = localStorage.getItem("userId");

const STORAGE_KEY = 'wordsPerGroup'
const learnNumber = parseInt(localStorage.getItem(STORAGE_KEY)) || 10
const words = ref([]);
const currentIndex = ref(0);
const isWrong = ref(false);
const isCorrect = ref(false);
const selectedOption = ref(null);
const shuffledOptions = ref([]);
const showCompletion = ref(false);
const showSpellingExercises = ref(false);
const endStudyTime = ref(null);
const startStudyTime = ref(null);

const UserStudyRecord = {
  user_id: 1,                  // 用户ID
  study_date: "2025-04-10",    // 学习日期 (YYYY-MM-DD)
  start_time: "2025-04-10 09:00:00",  // 学习开始时间
  end_time: "2025-04-10 09:30:00",    // 学习结束时间
  duration_minutes: 30,        // 学习时长，单位：分钟
  word_count: 500,             // 实际学习的单词数
  session_type: "study"        // 会话类型：学习（study）或复习（review）
}

// 计算进度百分比
const progressPercentage = computed(() => {
  return ((currentIndex.value + 1) / words.value.length) * 100;
});

const loadWords = async () => {
  try {
    const response = await getUnlearnedWords(userId, learnNumber);
    if (response.success) {
      words.value = response.words;
      // console.log("获取未学习的单词成功:", words.value);
      if (words.value.length === 0) {
        showCompletion.value = true;
        return;
      }
      currentIndex.value = 0;
      generateOptions();
      showCompletion.value = false;
    }
  } catch (error) {
    console.error("加载单词失败:", error);
  }
};

const generateOptions = () => {
  if (words.value.length > 0) {
    const correctWord = words.value[currentIndex.value];
    const options = [correctWord];
    while (options.length < 4) {
      const randomWord = words.value[Math.floor(Math.random() * words.value.length)];
      if (!options.includes(randomWord)) {
        options.push(randomWord);
      }
    }
    shuffledOptions.value = options.sort(() => Math.random() - 0.5);
  }
};

// 发音功能
const pronounceWord = () => {
  if ('speechSynthesis' in window) {
    const utterance = new SpeechSynthesisUtterance(words.value[currentIndex.value].word);
    utterance.lang = 'en-US';
    speechSynthesis.speak(utterance);
  } else {
    console.warn('浏览器不支持语音合成API');
  }
};
const calculateDurationMinutes = (startTime, endTime) => {
  // 把 "YYYY-MM-DD HH:MM:SS" 转换成 Date 对象
  const start = new Date(startTime.replace(/-/g, '/'));
  const end = new Date(endTime.replace(/-/g, '/'));

  // 计算时间差（毫秒）
  const diffMs = end - start;

  // 转换为分钟
  const minutes = Math.floor(diffMs / (1000 * 60));

  // 如果小于 1 分钟，强制返回 1
  return minutes < 1 ? 1 : minutes;
};

// function calculateDurationMinutes(startTime, endTime) {
//   // 把 "YYYY-MM-DD HH:MM:SS" 转换成 Date 对象
//   const start = new Date(startTime.replace(/-/g, '/'));
//   const end = new Date(endTime.replace(/-/g, '/'));

//   // 计算时间差（毫秒）
//   const diffMs = end - start;

//   // 转换为分钟
//   const minutes = Math.floor(diffMs / (1000 * 60));

//   return minutes;
// }
const submitStudyLog = async () => {
  const {
    user_id,
    study_date,
    start_time,
    end_time,
    duration_minutes,
    word_count,
    session_type
  } = UserStudyRecord;

  const result = await addStudyLogDataApi(
    user_id,
    study_date,
    start_time,
    end_time,
    duration_minutes,
    word_count,
    session_type
  );

  if (result.success) {
    console.log('✅ 学习日志添加成功:', result.message);
  } else {
    console.error('❌ 添加失败:', result.message);
  }
};
const checkAnswer = (option) => {
  if (selectedOption.value !== null) return;

  selectedOption.value = option;
  if (option.word_id === words.value[currentIndex.value].word_id) {
    isCorrect.value = true;
    isWrong.value = false;
    setTimeout(() => {
      if (currentIndex.value < words.value.length - 1) {
        currentIndex.value++;
        generateOptions();
        isCorrect.value = false;
        selectedOption.value = null;
      } else {
        saveLearnedWords(userId, words.value).then((response) => {
          // 获取当前的 UTC 时间
          const now = new Date();

          // 将时间调整到中国标准时间（UTC+8）
          now.setHours(now.getHours() + 8); // 调整为中国时间（CST）

          // 获取当前时间戳（毫秒）
          const endStudyTime = now.toISOString().slice(0, 19).replace("T", " ");
          UserStudyRecord.end_time = endStudyTime;

          UserStudyRecord.duration_minutes = calculateDurationMinutes(UserStudyRecord.start_time, endStudyTime)

          // console.log("China current time (timestamp):", UserStudyRecord);
          // UserStudyRecord.
          // console.log(response.message);
          submitStudyLog()
          showCompletion.value = true;
        });
      }
    }, 800);
  } else {
    isWrong.value = true;
    setTimeout(() => {
      isWrong.value = false;
      selectedOption.value = null;
    }, 800);
  }
};

// 重新学习
const restartLearning = () => {

  loadWords();
};

// 单词抽屉
const selectedWord = ref("");
const showDrawer = ref(false);

const openDrawer = async (word) => {
  if (showDrawer.value) {
    showDrawer.value = false;
    await nextTick();
  }
  selectedWord.value = word;
  setTimeout(() => {
    showDrawer.value = true;
  }, 10);
};


// note 抽屉
const showDrawerNote = ref(false);

const openDrawerNote = async (word) => {
  if (showDrawerNote.value) {
    showDrawerNote.value = false;
    await nextTick();
  }
  selectedWord.value = word;
  setTimeout(() => {
    showDrawerNote.value = true;
  }, 10);
};

const initStudyRecord = async () => {
  // 获取当前时间，并调整为中国时间（UTC+8）
  const now = new Date();
  now.setHours(now.getHours() + 8);  // 调整时区到 UTC+8（中国时间）
  UserStudyRecord.user_id = userId;
  UserStudyRecord.study_date = now.toISOString().slice(0, 10);  // 获取日期部分 YYYY-MM-DD
  UserStudyRecord.start_time = now.toISOString().slice(0, 19).replace("T", " ");  // 获取时间部分 YYYY-MM-DD HH:MM:SS
  startStudyTime.value = now.toISOString().slice(0, 19).replace("T", " ");
  UserStudyRecord.word_count = learnNumber;
  UserStudyRecord.session_type = 'study';
  // console.log(UserStudyRecord, 'UserStudyRecord');
}

onMounted(() => {
  // console.log(learnNumber, 'learnNumber');
  loadWords();
  initStudyRecord();
});


import { inject } from "vue";

const theme = inject("theme");
const setTheme = (newTheme) => {
  theme.value = newTheme; // 更新全局主题
};
</script>

<style scoped>
.my-component {
  .learning-app {


    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    color: var(--text-color);
    background-color: var(--bg-color);
    /* min-height: 100vh; */
    /* padding: 20px; */
  }

  .container {
    height: 85vh;

    max-width: 600px;
    margin: 0px auto;
    padding: 5vh;
    margin-top: 5vh;
    background-color: var(--card-bg);
    border-radius: 16px;
    box-shadow: 0 4px 20px var(--shadow-color);
    padding-bottom: 0;
  }

  /* 进度条 */
  .progress-indicator {
    width: 100%;
    height: 8px;
    background-color: var(--border-color);
    border-radius: 4px;
    margin-bottom: 24px;
    position: relative;
  }

  .progress-bar {
    height: 100%;
    background-color: var(--progress-color);
    border-radius: 4px;
    transition: width 0.3s ease;
  }

  .progress-text {
    position: absolute;
    right: 0;
    top: -25px;
    font-size: 14px;
    color: var(--hint-color);
  }

  /* 单词展示区域 */
  .word-display {
    text-align: center;
    margin-bottom: 32px;
    padding: 20px;
    border-radius: 12px;
    background-color: rgba(74, 107, 255, 0.05);
  }

  .word {
    font-size: 2.5rem;
    margin: 0 0 8px;
    color: var(--primary-color);
    font-weight: 700;
  }

  .word-meta {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 12px;
  }

  .phonetic {
    font-size: 1.2rem;
    color: var(--hint-color);
    margin: 0;
  }

  .pronounce-btn {
    background: none;
    border: none;
    color: var(--primary-color);
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 4px;
    border-radius: 50%;
    transition: all 0.2s;
  }

  .pronounce-btn:hover {
    background-color: rgba(74, 107, 255, 0.1);
    transform: scale(1.1);
  }

  /* 选项区域 */
  .options {
    list-style: none;
    padding: 0;
    margin: 0 0 24px;
    width: 100%;
  }

  .option {
    display: flex;
    align-items: center;
    padding: 16px 20px;
    margin-bottom: 12px;
    background-color: var(--card-bg);
    border: 1px solid var(--border-color);
    border-radius: 12px;
    cursor: pointer;
    transition: all 0.2s;
    position: relative;
    overflow: hidden;
  }

  .option:hover:not(.disabled) {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px var(--shadow-color);
    border-color: var(--primary-color);
  }

  .option-number {
    width: 28px;
    height: 28px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: var(--border-color);
    color: var(--hint-color);
    border-radius: 50%;
    margin-right: 16px;
    font-weight: 600;
    flex-shrink: 0;
  }

  .option-text {
    flex-grow: 1;
    text-align: left;
  }

  .option.correct {
    background-color: rgba(76, 175, 80, 0.1);
    border-color: var(--correct-color);
    color: var(--correct-color);
  }

  .option.correct .option-number {
    background-color: var(--correct-color);
    color: white;
  }

  .option.wrong {
    background-color: rgba(244, 67, 54, 0.1);
    border-color: var(--wrong-color);
    color: var(--wrong-color);
  }

  .option.wrong .option-number {
    background-color: var(--wrong-color);
    color: white;
  }

  .option.disabled {
    cursor: not-allowed;
    opacity: 0.7;
  }

  /* 提示按钮 */
  .hint-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    width: 100%;
    padding: 12px;
    background: none;
    border: 1px dashed var(--hint-color);
    border-radius: 12px;
    color: var(--hint-color);
    cursor: pointer;
    transition: all 0.2s;
    font-size: 1rem;
  }

  .hint-btn:hover {
    background-color: rgba(107, 114, 128, 0.05);
    border-style: solid;
  }

  /* 完成界面 */
  .completion-screen {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    padding: 20px;
  }

  .completion-content {
    max-width: 500px;
    width: 100%;
    background-color: var(--card-bg);
    padding: 40px;
    border-radius: 16px;
    box-shadow: 0 4px 20px var(--shadow-color);
    text-align: center;
  }

  .celebration-icon {
    font-size: 4rem;
    margin-bottom: 20px;
    animation: bounce 1s infinite alternate;
  }

  @keyframes bounce {
    from {
      transform: translateY(0);
    }

    to {
      transform: translateY(-15px);
    }
  }

  .completion-screen h2 {
    font-size: 2rem;
    margin: 0 0 12px;
    color: var(--primary-color);
  }

  .completion-screen p {
    font-size: 1.1rem;
    color: var(--hint-color);
    margin-bottom: 30px;
  }

  .completion-actions {
    display: flex;
    gap: 16px;
    justify-content: center;
  }

  .completion-btn {
    padding: 12px 24px;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s;
    text-decoration: none;
    display: inline-block;
  }

  .home-btn {
    background-color: var(--primary-color);
    color: white;
    border: none;
  }

  .home-btn:hover {
    background-color: #3a5bef;
    transform: translateY(-2px);
  }

  .restart-btn {
    background-color: white;
    color: var(--primary-color);
    border: 1px solid var(--primary-color);
  }

  .restart-btn:hover {
    background-color: rgba(74, 107, 255, 0.1);
    transform: translateY(-2px);
  }

  /* 加载状态 */
  .loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
  }

  .spinner {
    width: 50px;
    height: 50px;
    border: 5px solid var(--border-color);
    border-top-color: var(--primary-color);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20px;
  }

  @keyframes spin {
    to {
      transform: rotate(360deg);
    }
  }

  .loading-state p {
    font-size: 1.2rem;
    color: var(--hint-color);
  }

  /* 响应式设计 */
  @media (max-width: 640px) {
    .container {
      padding: 16px;
    }

    .word {
      font-size: 2rem;
    }

    .option {
      padding: 14px 16px;
    }

    .completion-actions {
      flex-direction: column;
      gap: 12px;
    }

    .completion-btn {
      width: 100%;
    }
  }
}
</style>